package com.nq.utils.task.stock;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nq.common.constant.WebsocketConst;
import com.nq.common.entity.StStockTickerDetails;
import com.nq.common.entity.StStockTickerKLineList;
import com.nq.common.entity.State;
import com.nq.common.entity.info.StockTickerListInfo;
import com.nq.common.entity.vo.StStockTickerDetailsVo;
import com.nq.dao.StockMapper;
import com.nq.dao.stock.StStockTickerMapper;
import com.nq.message.websocket.WebSocket;
import com.nq.message.websocket.WebSocketUtils;
import com.nq.pojo.SiteSetting;
import com.nq.pojo.Stock;
import com.nq.service.ISiteSettingService;
import com.nq.service.IStockService;
import com.nq.stock.entity.KLineDetail;
import com.nq.stock.entity.StStockTicker;
import com.nq.stock.service.IStStockTickerService;
import com.nq.stock.vo.StStockIndexVo;
import com.nq.stock.vo.StStockTickerKLineVO;
import com.nq.utils.DateTimeUtil;
import com.nq.utils.HttpClientRequest;
import com.nq.utils.PropertiesUtil;
import com.nq.utils.redis.RedisShardedPoolUtils;
import com.nq.utils.stock.BuyAndSellUtils;
import com.nq.utils.stock.pinyin.GetPyByChinese;
import com.nq.utils.task.tsanghi.StocksComponent;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.util.*;
//import org.springframework.scheduling.annotation.Scheduled;


@Component
public class StockTask {

    // 股票列表实时数据
    public static final String ST_STOCK_TICKER_REAL_TIME_DATA_LIST_KEY = "real_time_data_list_key:";
    // 指数列表实时数据
    public static final String ST_STOCK_TICKER_REAL_TIME_DATA_INDEX_KEY = "real_time_data_index_key:";
    // 股票详情实时数据
    public static final String ST_STOCK_TICKER_REAL_TIME_DATA_DETAIL_KEY = "real_time_data_detail_key:";
    // 股票详情K线数据
    public static final String ST_STOCK_TICKER_REAL_TIME_DATA_DETAIL_KLINE_KEY = "real_time_data_detail_kline_key:";
    // 收藏列表
    public static final String ST_STOCK_OPTION_REAL_TIME_DATA_LIST_KEY = "real_time_data_option_key:";

    @Autowired
    IStockService stockService;
    @Autowired
    private IStStockTickerService stStockTickerService;
    @Autowired
    private StStockTickerMapper stStockTickerMapper;
    @Autowired
    StockMapper stockMapper;

    @Resource
    private ISiteSettingService siteSettingService;

    private static StocksComponent stocksComponent;
    @Autowired
    public void setStocksComponent(StocksComponent stocksComponent) {
        StockTask.stocksComponent = stocksComponent;
    }

    private static final Logger log = LoggerFactory.getLogger(StockTask.class);

    @Autowired
    private WebSocket webSocket;

    // 上午 9:30 至 11:30 每 5 秒执行一次
    @Scheduled(cron = "*/5 0-30 10-12 * * MON-FRI")
    public void executeStockTaskMorning() {
        // 这里编写上午时间段的任务逻辑
        log.info("执行上午股票WS相关任务开始");
        pushStockListDataToClient();
        pushStockDetailDataToClient();
        pushStockIndexDataToClient();
        log.info("执行上午股票WS相关任务结束");
    }

    // 下午 13:00 至 14:59 每 5 秒执行一次
    @Scheduled(cron = "*/5 0-59 14-16 * * MON-FRI")
    public void executeStockTaskAfternoon() {
        // 这里编写下午 1 点到 2 点 59 分时间段的任务逻辑
        log.info("执行下午股票WS相关任务开始");
        pushStockListDataToClient();
        pushStockDetailDataToClient();
        pushStockIndexDataToClient();
        log.info("执行下午股票WS相关任务结束");
    }

    /**
     * 定时推送股票详情实时行情
     */
//    @Scheduled(cron = "*/5 30-59 9-11 * * MON-FRI,*/5 0-59 13-14 * * MON-FRI,*/5 0 15 * * MON-FRI")
    public void pushStockDetailDataToClient() {
        try {
            log.info("############定时推送股票详情实时行情开始######################");
            List<String> keysByPrefix = RedisShardedPoolUtils.getKeys(ST_STOCK_TICKER_REAL_TIME_DATA_DETAIL_KEY);
            if (null == keysByPrefix || keysByPrefix.isEmpty()) {
                return;
            }
            for (String key : keysByPrefix) {
                String[] splitKey = key.split(":");
                List<String> stringList = Arrays.asList(splitKey);
                if (stringList.size() == 2) {
                    String userId = stringList.get(1);

                    // 获取以ST_STOCK_TICKER_REAL_TIME_DATA_DETAIL_KEY开头的所有数据
                    String detailMessage = RedisShardedPoolUtils.get(key);
                    if (StringUtils.isNotBlank(detailMessage)) {
                        // 处理查询股票列表的数据格式
                        String[] marketAndCode = detailMessage.split(";");
                        List<String> marketAndCodeList = Arrays.asList(marketAndCode);
                        if (marketAndCodeList.size() > 0) {
                            String market = marketAndCodeList.get(1);
                            String code = marketAndCodeList.get(2);


                            StStockTickerDetailsVo stStockTickerDetailsVo = stStockTickerService.queryDetails(market, code);
                            if (null  != stStockTickerDetailsVo) {
                                Session session = WebSocketUtils.getSession();
                                if (null != session && session.isOpen()) {
                                    JSONObject obj = new JSONObject();
                                    obj.put(WebsocketConst.NEWS_PUBLISH, WebsocketConst.STOCK_DETAIL_TICKER);//业务类型
                                    obj.put(WebsocketConst.MSG_TXT, stStockTickerDetailsVo);//消息内容
                                    webSocket.sendOneMessage(userId,  obj.toJSONString());
                                    log.info("############定时推送股票详情实时行情: "+userId+"######################");

                                }

                            }
                        }
                    }
                }
            }
            log.info("############定时推送股票详情实时行情结束######################");

        }catch (Exception e) {
            log.error("获取定时推送股票详情实时行情失败", e);
        }

    }

    /**
     * 定时推送股票详情K线实时行情
     */
//    @Scheduled(cron = "0/10 * * * * ?")
    public void pushStockDetailKLineDataToClient() {
        try {
            log.info("############定时推送股票详情K线实时行情开始######################");
            List<String> keysByPrefix = RedisShardedPoolUtils.getKeys(ST_STOCK_TICKER_REAL_TIME_DATA_DETAIL_KLINE_KEY);
            for (String key : keysByPrefix) {
                String[] splitKey = key.split(":");
                List<String> stringList = Arrays.asList(splitKey);
                if (stringList.size() == 2) {
                    String userId = stringList.get(1);

                    String detailMessage = RedisShardedPoolUtils.get(key);
                    if (StringUtils.isNotBlank(detailMessage)) {
                        // 处理查询股票列表的数据格式
                        String[] marketAndCode = detailMessage.split(";");
                        List<String> marketAndCodeList = Arrays.asList(marketAndCode);
                        if (marketAndCodeList.size() > 0) {
                            String market = marketAndCodeList.get(1);
                            String code = marketAndCodeList.get(2);
                            // 按时分秒 获取K线
                            String interval = marketAndCodeList.get(3);


                            StStockTickerKLineVO stStockTickerKLineVO = stStockTickerService.queryKLineDetails(market, code, interval, "1");
                            if (null  != stStockTickerKLineVO) {
                                Session session = WebSocketUtils.getSession();
                                if (null != session && session.isOpen()) {
                                    JSONObject obj = new JSONObject();
                                    obj.put(WebsocketConst.NEWS_PUBLISH, WebsocketConst.STOCK_DETAIL_KLINE_TICKER);//业务类型
                                    obj.put(WebsocketConst.MSG_TXT, stStockTickerKLineVO);//消息内容
                                    webSocket.sendOneMessage(userId,  obj.toJSONString());
                                    log.info("############定时推送股票详情K线实时行情: "+userId+"######################");

                                }

                            }
                        }
                    }
                }
            }
            log.info("############定时推送股票详情K线实时行情结束######################");

        }catch (Exception e) {
            log.error("获取定时推送股票详情实时行情失败", e);
        }

    }

    /**
     * 定时推送股票指数实时行情
     */
//    @Scheduled(cron = "*/5 30-59 9-11 * * MON-FRI,*/5 0-59 13-14 * * MON-FRI,*/5 0 15 * * MON-FRI")
    public void pushStockIndexDataToClient() {
        try {
            log.info("############定时推送股票指数实时行情开始######################");
            List<String> keysByPrefix = RedisShardedPoolUtils.getKeys(ST_STOCK_TICKER_REAL_TIME_DATA_INDEX_KEY);
            if (null == keysByPrefix || keysByPrefix.isEmpty()) {
                return;
            }
            for (String key : keysByPrefix) {
                String[] splitKey = key.split(":");
                List<String> stringList = Arrays.asList(splitKey);
                if (stringList.size() == 2) {
                    String userId = stringList.get(1);

                    String indexMessage = RedisShardedPoolUtils.get(key);
                    if (StringUtils.isNotBlank(indexMessage)) {
                        String[] indexMarketAndCode = indexMessage.split(";");
                        List<String> indexMarketAndCodeList = Arrays.asList(indexMarketAndCode);
                        if (indexMarketAndCodeList.size() == 3) {
                            // 获取指数数据
                            // 如果非交易时间直接查数据库
                            SiteSetting siteSetting = siteSettingService.getSiteSetting();
                            if(null == siteSetting){
                                throw new RuntimeException("网站设置没有数据");
                            }

                            List<StStockTickerKLineList> inIndexKLineList = new ArrayList<>();
                            try {
                                String transAmBegin = siteSetting.getTransAmBegin();
                                String transAmEnd = siteSetting.getTransAmEnd();
                                String transPmBegin = siteSetting.getTransPmBegin();
                                String transPmEnd = siteSetting.getTransPmEnd();

                                boolean am = false;
                                boolean pm = false;
                                am = BuyAndSellUtils.isTransTime(transAmBegin, transAmEnd);
                                pm = BuyAndSellUtils.isTransTime(transPmBegin, transPmEnd);
                                log.info("am = {}  pm = {}", Boolean.valueOf(am), Boolean.valueOf(pm));
                                if (am || pm) {
                                    StStockTickerKLineList sensex = stocksComponent.queryKLineDetailsByMarketAndCode(StocksComponent.HOSEIN, StocksComponent.HOSEIN_VN30_INDEX, "1min", "1");
                                    inIndexKLineList.add(sensex);
                                    StStockTickerKLineList dji = stocksComponent.queryKLineDetailsByMarketAndCode(StocksComponent.HOSEIN, StocksComponent.HOSEIN_HNXINDEX_INDEX, "1min", "1");
                                    inIndexKLineList.add(dji);
                                    StStockTickerKLineList sz300 = stocksComponent.queryKLineDetailsByMarketAndCode(StocksComponent.HOSEIN, StocksComponent.HOSEIN_VNINDEX_INDEX, "1min", "1");
                                    inIndexKLineList.add(sz300);
                                }
                            } catch (Exception e) {
                                log.error("定时推送指数查询详情时，判断交易时间出错！");
                                throw new RuntimeException(e);
                            }




                            // 发送到前端
                            List<StStockTickerKLineList> totalIndexList = new ArrayList<>();
                            if (null != inIndexKLineList) {
                                totalIndexList.addAll(inIndexKLineList);
                            }

                            if (totalIndexList.size() > 0) {
                                List<StStockIndexVo> stStockIndexVos = new ArrayList<>();
                                // 转换格式
                                for (StStockTickerKLineList kLineList : totalIndexList) {
                                    String data = kLineList.getData();
                                    if (StringUtils.isBlank(data)) {
                                        continue;
                                    }
                                    // 最终数据 包含K线 当前价格 涨跌幅
                                    StStockIndexVo stStockIndexVo = new StStockIndexVo();

                                    // K线数据
                                    StStockTickerKLineVO kLineVO = new StStockTickerKLineVO();
                                    String[] splitData = data.split(";");
                                    List<String> dataList = Arrays.asList(splitData);

                                    List<KLineDetail> dataDetails = new ArrayList<>();
                                    // 处理具体的字段  1时间戳,1昨日收,1今日开,1最高,1最低,1交易额,1交易量;
                                    for (String obj : dataList) {
                                        String[] split = obj.split(",");
                                        List<String> strings = Arrays.asList(split);
                                        if (strings.size() < 7) {
                                            continue;
                                        }
                                        KLineDetail kLineDetail = new KLineDetail();
                                        kLineDetail.setTimestamp(String.valueOf(Long.parseLong(strings.get(0))*1000));
                                        kLineDetail.setClose(strings.get(1));
                                        kLineDetail.setOpen(strings.get(2));
                                        kLineDetail.setHigh(strings.get(3));
                                        kLineDetail.setLow(strings.get(4));
                                        kLineDetail.setTurnover(strings.get(5));
                                        kLineDetail.setVolume(strings.get(6));
                                        dataDetails.add(kLineDetail);
                                    }

                                    BeanUtils.copyProperties(kLineList, kLineVO);
                                    kLineVO.setData(dataDetails);

                                    BeanUtils.copyProperties(kLineVO, stStockIndexVo);


                                    String code = kLineList.getCode();
                                    String market = kLineList.getMarket();
                                    StStockTickerDetails inStockTickerListInfo = stocksComponent.queryDetailsByMarketAndCode(market, code);
                                    // stocksComponent.thirdInterfaceStatistic(StocksComponent.MINI_PRICES, "pushStockIndexDataToClient");

                                    if (null != inStockTickerListInfo) {
                                        StockTickerListInfo infoData = inStockTickerListInfo.getData();
                                        if (null != infoData){
                                            stStockIndexVo.setPrice(infoData.getPrice());
                                            stStockIndexVo.setUp(infoData.getUp());
                                            stStockIndexVo.setChange(infoData.getChange());
                                        }
                                    }

                                    stStockIndexVos.add(stStockIndexVo);
                                }

                                Session session = WebSocketUtils.getSession();
                                if (null != session && session.isOpen()) {
                                    JSONObject obj = new JSONObject();
                                    obj.put(WebsocketConst.NEWS_PUBLISH, WebsocketConst.STOCK_INDEX_TICKER);//业务类型
                                    obj.put(WebsocketConst.MSG_TXT, stStockIndexVos);//消息内容
                                    webSocket.sendOneMessage(userId, obj.toJSONString());
                                    log.info("############推送股票指数实时行情: "+userId+"######################");
                                }
                            }
                        }
                    }


                }
            }
            log.info("############定时推送股票指数实时行情结束######################");

        }catch (Exception e) {
            log.error("获取定时推送股票指数实时行情失败", e);
        }

    }
    /**
     * 定时推送股票列表实时行情
     */
//    @Scheduled(cron = "*/5 30-59 9-11 * * MON-FRI,*/5 0-59 13-14 * * MON-FRI,*/5 0 15 * * MON-FRI")
    public void pushStockListDataToClient() {

        log.info("############定时推送股票列表实时行情开始######################");
        List<String> keysByPrefix = RedisShardedPoolUtils.getKeys(ST_STOCK_TICKER_REAL_TIME_DATA_LIST_KEY);
        if (null == keysByPrefix || keysByPrefix.isEmpty()) {
            return;
        }

        for (String key : keysByPrefix) {
            String[] splitKey = key.split(":");
            List<String> stringList = Arrays.asList(splitKey);
            if (stringList.size() == 2) {
                String userId = stringList.get(1);

                // 从适当的来源获取最新的 market 和 stockCodes
                String listMessage = RedisShardedPoolUtils.get(key);
                try {
                    if (StringUtils.isNotBlank(listMessage)) {
                        // 处理查询股票列表的数据格式
                        String[] marketAndCode = listMessage.split(";");
                        List<String> marketAndCodeList = Arrays.asList(marketAndCode);
                        if (marketAndCodeList.size() == 6) {

                            String country = marketAndCodeList.get(1);
                            String changePercent = marketAndCodeList.get(2);
                            String pageNo = marketAndCodeList.get(3);
                            String pageSize = marketAndCodeList.get(4);

                            // 查询列表
                            QueryWrapper<StStockTicker> queryWrapper = new QueryWrapper<>();
                            if (StringUtils.isNotBlank(country)) {
                                // 查询 SH  SZ 交易所数据
                                queryWrapper.and(qw -> qw.eq("market", country));
                            }

                            int pageNumI = Integer.parseInt(pageNo);
                            int pageSizeI = Integer.parseInt(pageSize);
                            int total = pageNumI * pageSizeI;


                            // 按照涨跌幅排序
                            if (State.STATE_S1.equals(changePercent)) {
                                queryWrapper.orderByAsc("up");
                            } else {
                                queryWrapper.orderByDesc("up");
                            }
                            queryWrapper.last("limit " + total);


                            List<StStockTicker> stockTickers = stStockTickerMapper.selectList(queryWrapper);

                            // 存储详情
                            ArrayList<StockTickerListInfo> infos = new ArrayList<>();

                            // 判断交易时间
                            SiteSetting siteSetting = siteSettingService.getSiteSetting();

                            // 股票的交易时间
                            String transAmBegin = siteSetting.getTransAmBegin();
                            String transAmEnd = siteSetting.getTransAmEnd();
                            String transPmBegin = siteSetting.getTransPmBegin();
                            String transPmEnd = siteSetting.getTransPmEnd();

                            boolean am = false;
                            boolean pm = false;
                            am = BuyAndSellUtils.isTransTime(transAmBegin, transAmEnd);
                            pm = BuyAndSellUtils.isTransTime(transPmBegin, transPmEnd);
                            log.info("am = {}  pm = {}", Boolean.valueOf(am), Boolean.valueOf(pm));
                            if (!am && !pm) {
                                log.info("am = {}  pm = {}", Boolean.valueOf(am), Boolean.valueOf(pm) + "股票不在交易时间内");
                                for (StStockTicker stStockTicker : stockTickers) {
                                    StockTickerListInfo tickerListInfo = new StockTickerListInfo();
                                    BeanUtils.copyProperties(stStockTicker, tickerListInfo);
                                    infos.add(tickerListInfo);
                                }

                                if (!infos.isEmpty()) {
                                    Session session = WebSocketUtils.getSession();
                                    if(null != session && session.isOpen()) {

                                        JSONObject obj = new JSONObject();
                                        obj.put(WebsocketConst.NEWS_PUBLISH, WebsocketConst.STOCK_LIST_TICKER);//业务类型
                                        obj.put(WebsocketConst.MSG_TXT, infos);//消息内容
                                        webSocket.sendOneMessage(userId, obj.toJSONString());
                                    }
                                }
                                continue;
                            }


                            for (StStockTicker stStockTicker : stockTickers) {
                                String market = stStockTicker.getMarket();
                                String code = stStockTicker.getCode();

                                if (market != null && code != null) {
                                    StStockTickerDetails details = stocksComponent.queryDetailsByMarketAndCode(market, code);
                                    // stocksComponent.thirdInterfaceStatistic(StocksComponent.MINI_PRICES, "pushStockListDataToClient");

                                    if (null != details) {
                                        StockTickerListInfo data = details.getData();
                                        if (null != data) {
                                            infos.add(data);
                                        }
                                    }
                                }
                            }

                            if (!infos.isEmpty()) {
                                Session session = WebSocketUtils.getSession();
                                if(null != session && session.isOpen()) {

                                    JSONObject obj = new JSONObject();
                                    obj.put(WebsocketConst.NEWS_PUBLISH, WebsocketConst.STOCK_LIST_TICKER);//业务类型
                                    obj.put(WebsocketConst.MSG_TXT, infos);//消息内容
                                    webSocket.sendOneMessage(userId, obj.toJSONString());
                                }
                            }

                        }
                    }

                } catch (Exception e) {
                    log.error("获取股票列表实时刷新定时任务失败", e);
                }
            }
        }

    }


    /*股票走勢圖定時任務-15*/
//    @Scheduled(cron = "0 0/1 9-15 * * ?")
    public void z1() {
        boolean am = false;
        boolean pm = false;
        try {
            am = BuyAndSellUtils.isTransTime("9:29", "11:31");
            pm = BuyAndSellUtils.isTransTime("12:59", "15:00");
        } catch (Exception e) {
            log.error("= {}", e);
        }
        log.info("am = {}  pm = {}", Boolean.valueOf(am), Boolean.valueOf(pm));
        if (am || pm) {
            log.info("=====z1={} =====", DateTimeUtil.dateToStr(new Date()));
            this.stockService.z1();
            log.info("=====z1={} =====", DateTimeUtil.dateToStr(new Date()));
        }
    }

//    @Scheduled(cron = "0 0/1 9-15 * * ?")
    public void z11() {
        boolean am = false;
        boolean pm = false;
        try {
            am = BuyAndSellUtils.isTransTime("9:29", "11:31");
            pm = BuyAndSellUtils.isTransTime("12:59", "15:00");
        } catch (Exception e) {
            log.error("= {}", e);
        }
        log.info(" am = {}  pm = {}", Boolean.valueOf(am), Boolean.valueOf(pm));
        if (am || pm) {
            log.info("====z11={} =====", DateTimeUtil.dateToStr(new Date()));
            this.stockService.z11();
            log.info("====z11={} =====", DateTimeUtil.dateToStr(new Date()));
        }
    }

//    @Scheduled(cron = "0 0/1 9-15 * * ?")
    public void z12() {
        boolean am = false;
        boolean pm = false;
        try {
            am = BuyAndSellUtils.isTransTime("9:29", "11:31");
            pm = BuyAndSellUtils.isTransTime("12:59", "15:00");
        } catch (Exception e) {
            log.error("= {}", e);
        }
        log.info("z12 am = {}  pm = {}", Boolean.valueOf(am), Boolean.valueOf(pm));
        if (am || pm) {
            log.info("====z12={} =====", DateTimeUtil.dateToStr(new Date()));
            this.stockService.z12();
            log.info("====z12={} =====", DateTimeUtil.dateToStr(new Date()));
        }
    }

//    @Scheduled(cron = "0 0/1 9-15 * * MON-FRI")
    public void z2() {
        boolean am = false;
        boolean pm = false;
        try {
            am = BuyAndSellUtils.isTransTime("9:29", "11:31");
            pm = BuyAndSellUtils.isTransTime("12:59", "15:00");
        } catch (Exception e) {
            log.error("= {}", e);
        }
        log.info("am = {}  pm = {}", Boolean.valueOf(am), Boolean.valueOf(pm));
        if (am || pm) {
            log.info("=====z2{} =====", DateTimeUtil.dateToStr(new Date()));
            this.stockService.z2();
            log.info("=====z2{} =====", DateTimeUtil.dateToStr(new Date()));
        }
    }

//    @Scheduled(cron = "0 0/1 9-15 * * MON-FRI")
    public void z21() {
        boolean am = false;
        boolean pm = false;
        try {
            am = BuyAndSellUtils.isTransTime("9:29", "11:31");
            pm = BuyAndSellUtils.isTransTime("12:59", "15:00");
        } catch (Exception e) {
            log.error("= {}", e);
        }
        log.info("z21-am = {}  pm = {}", Boolean.valueOf(am), Boolean.valueOf(pm));
        if (am || pm) {
            log.info("===z21=={} =====", DateTimeUtil.dateToStr(new Date()));
            this.stockService.z21();
            log.info("===z21=={} =====", DateTimeUtil.dateToStr(new Date()));
        }
    }

//    @Scheduled(cron = "0 0/1 9-15 * * MON-FRI")
    public void z22() {
        boolean am = false;
        boolean pm = false;
        try {
            am = BuyAndSellUtils.isTransTime("9:29", "11:31");
            pm = BuyAndSellUtils.isTransTime("12:59", "15:00");
        } catch (Exception e) {
            log.error("= {}", e);
        }
        log.info("z22-am = {}  pm = {}", Boolean.valueOf(am), Boolean.valueOf(pm));
        if (am || pm) {
            log.info("====z22={} =====", DateTimeUtil.dateToStr(new Date()));
            this.stockService.z22();
            log.info("====z22={} =====", DateTimeUtil.dateToStr(new Date()));
        }
    }

//    @Scheduled(cron = "0 0/1 9-15 * * MON-FRI")
    public void z3() {
        boolean am = false;
        boolean pm = false;
        try {
            am = BuyAndSellUtils.isTransTime("9:29", "11:31");
            pm = BuyAndSellUtils.isTransTime("12:59", "15:00");
        } catch (Exception e) {
            log.error("= {}", e);
        }
        log.info("am = {}  pm = {}", Boolean.valueOf(am), Boolean.valueOf(pm));
        if (am || pm) {
            log.info("====z3={} =====", DateTimeUtil.dateToStr(new Date()));
            this.stockService.z3();
            log.info("====z3={} =====", DateTimeUtil.dateToStr(new Date()));
        }
    }

//    @Scheduled(cron = "0 0/1 9-15 * * MON-FRI")
    public void z31() {
        boolean am = false;
        boolean pm = false;
        try {
            am = BuyAndSellUtils.isTransTime("9:29", "11:31");
            pm = BuyAndSellUtils.isTransTime("12:59", "15:00");
        } catch (Exception e) {
            log.error("= {}", e);
        }
        log.info("z31-am = {}  pm = {}", Boolean.valueOf(am), Boolean.valueOf(pm));
        if (am || pm) {
            log.info("====z31={} =====", DateTimeUtil.dateToStr(new Date()));
            this.stockService.z31();
            log.info("===z31=={} =====", DateTimeUtil.dateToStr(new Date()));
        }
    }

//    @Scheduled(cron = "0 0/1 9-15 * * MON-FRI")
    public void z32() {
        boolean am = false;
        boolean pm = false;
        try {
            am = BuyAndSellUtils.isTransTime("9:29", "11:31");
            pm = BuyAndSellUtils.isTransTime("12:59", "15:00");
        } catch (Exception e) {
            log.error("= {}", e);
        }
        log.info("z32-am = {}  pm = {}", Boolean.valueOf(am), Boolean.valueOf(pm));
        if (am || pm) {
            log.info("====z32={} =====", DateTimeUtil.dateToStr(new Date()));
            this.stockService.z32();
            log.info("====z32={} =====", DateTimeUtil.dateToStr(new Date()));
        }
    }

//    @Scheduled(cron = "0 0/1 9-15 * * MON-FRI")
    public void z4() {
        boolean am = false;
        boolean pm = false;
        try {
            am = BuyAndSellUtils.isTransTime("9:29", "11:31");
            pm = BuyAndSellUtils.isTransTime("12:59", "15:00");
        } catch (Exception e) {
            log.error("= {}", e);
        }
        log.info("am = {}  pm = {}", Boolean.valueOf(am), Boolean.valueOf(pm));
        if (am || pm) {
            log.info("====z4={} =====", DateTimeUtil.dateToStr(new Date()));
            this.stockService.z4();
            log.info("====z4={} =====", DateTimeUtil.dateToStr(new Date()));
        }
    }

//    @Scheduled(cron = "0 0/1 9-15 * * MON-FRI")
    public void z41() {
        boolean am = false;
        boolean pm = false;
        try {
            am = BuyAndSellUtils.isTransTime("9:29", "11:31");
            pm = BuyAndSellUtils.isTransTime("12:59", "15:00");
        } catch (Exception e) {
            log.error("= {}", e);
        }
        log.info("z41-am = {}  pm = {}", Boolean.valueOf(am), Boolean.valueOf(pm));
        if (am || pm) {
            log.info("====z41={} =====", DateTimeUtil.dateToStr(new Date()));
            this.stockService.z41();
            log.info("====z41={} =====", DateTimeUtil.dateToStr(new Date()));
        }
    }

//    @Scheduled(cron = "0 0/1 9-15 * * MON-FRI")
    public void z42() {
        boolean am = false;
        boolean pm = false;
        try {
            am = BuyAndSellUtils.isTransTime("9:29", "11:31");
            pm = BuyAndSellUtils.isTransTime("12:59", "15:00");
        } catch (Exception e) {
            log.error("= {}", e);
        }
        log.info("z42-am = {}  pm = {}", Boolean.valueOf(am), Boolean.valueOf(pm));
        if (am || pm) {
            log.info("====z42={} =====", DateTimeUtil.dateToStr(new Date()));
            this.stockService.z42();
            log.info("===z42=={} =====", DateTimeUtil.dateToStr(new Date()));
        }
    }

    //每天24点执行 同步股票数据 查漏补缺
//    @Scheduled(cron = "0 0 0 * * ?")
//    @Scheduled(cron = "0/1 * * * * ?")

//    @Scheduled(cron = "0 7 0 * * ?")
    public void syncStockData() throws InterruptedException {

        /**
         * sh_a https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=80&sort=symbol&asc=1&node=sh_a&symbol=&_s_r_a=init
         * sz_a https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=80&sort=symbol&asc=1&node=sz_a&symbol=&_s_r_a=init
         * hs_bjs https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=80&sort=symbol&asc=1&node=hs_bjs&symbol=&_s_r_a=init
         * cyb https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=80&sort=symbol&asc=1&node=cyb&symbol=&_s_r_a=init
         * kcb https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=80&sort=symbol&asc=1&node=kcb&symbol=&_s_r_a=init
         * 总条数 https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeStockCount?node=hs_bjs
         */
        log.info("====={股票同步任务开启} =====", DateTimeUtil.dateToStr(new Date()));
        String[] keys = {"sh_a", "sz_a", "hs_bjs", "cyb", "kcb"};
        for (String key : keys) {
            StringBuilder sb = new StringBuilder();
            int pageNumber = 34;
            String num = null;
            try {
                num = HttpClientRequest.doGet("https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeStockCount?node=" + key);
            } catch (Exception e) {
                log.error("计算页码请求出错", e);
                Thread.sleep(30000L);
                num = HttpClientRequest.doGet("https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeStockCount?node=" + key);
            }
            if (num != null) {
                num = num.substring(1, num.length() - 1);
                int total = Integer.parseInt(num);
                if (total % 80 == 0) {
                    pageNumber = total / 80;
                } else {
                    pageNumber = total / 80 + 1;
                }
            }

            try {
                String result = null;
                try {
                    result = HttpClientRequest.doGet("https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=" + pageNumber + "&num=80&sort=symbol&asc=1&node=" + key + "&symbol=&_s_r_a=init");
                } catch (Exception e) {
                    log.error("请求失败" + e);
                    Thread.sleep(30000L);
                    result = HttpClientRequest.doGet("https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=" + pageNumber + "&num=80&sort=symbol&asc=1&node=" + key + "&symbol=&_s_r_a=init");
                }

                JSONArray hsArray = JSONObject.parseArray(result);
//                    log.info("类型"+key +"数量"+hsArray.size()+"页码"+pageNumber+"内容"+hsArray);
                for (Object o : hsArray) {
                    JSONObject hsjson = JSONObject.parseObject(o.toString());
//                    log.info("代碼"+hsjson.getString("code"));
                    Stock stock = stockMapper.findStockByCode(hsjson.getString("code"));
//                        log.info("stock = {}", stock);
                    if (stock == null) {
                        stock = new Stock();
                        String type = hsjson.getString("symbol").substring(0, 2);
                        String spell = GetPyByChinese.converterToFirstSpell(hsjson.getString("name"));
                        stock.setStockCode(hsjson.getString("code"));
                        stock.setStockName(hsjson.getString("name"));
                        stock.setStockType(type);
                        stock.setStockGid(hsjson.getString("symbol"));
                        stock.setStockSpell(spell);
                        stock.setIsLock(0);
                        stock.setIsShow(0);
                        stock.setDataBase(0);
                        stock.setAddTime(new Date());
                        stockMapper.insert1(stock);
                        sb.append("新增股票：").append(stock.getStockName()).append(stock.getStockCode()).append("/n");
                    }

                    if ("cyb".equals(key) && stock.getStockPlate() == null) {
                        stock.setStockPlate("创业");
                        stockMapper.updateById(stock);
                    } else if ("kcb".equals(key) && stock.getStockPlate() == null) {
                        stock.setStockPlate("科创");
                        stockMapper.updateById(stock);
                    }

                }

            } catch (Exception e) {
                log.error("同步出错", e);


            }
            log.info(key + "股新增股票：{}", sb.toString());
        }
        log.info("====={股票同步任务结束} =====", DateTimeUtil.dateToStr(new Date()));

    }

    /**
     * 美股港股同步
     */
//    @Scheduled(cron = "0 5 0 * * ?")
    public void syncOtherStockData() {
        String[] keys = {"hk", "us"};
        long now = System.currentTimeMillis();
        String url;
        String result = null;
        com.alibaba.fastjson2.JSONObject json;
        for (String key : keys) {
            StringBuilder sb = new StringBuilder();
            if ("hk".equals(key)) {
                url = PropertiesUtil.getProperty("hk.stock.url") + now;
                result = HttpClientRequest.doGet(url);
                json = com.alibaba.fastjson2.JSONObject.parseObject(result);
            } else {
                url = PropertiesUtil.getProperty("us.stock.url") + now;
                result = HttpClientRequest.doGet(url);
                String da = result.substring(result.indexOf("(") + 1, result.indexOf(");"));
                json = com.alibaba.fastjson2.JSONObject.parseObject(da);
            }
            ArrayList diff = (ArrayList) json.getJSONObject("data").get("diff");
//            log.info("开始存库");
            for (Object o : diff) {
                com.alibaba.fastjson2.JSONObject data = (com.alibaba.fastjson2.JSONObject) o;
                String stockCode = data.getString("f12");

                Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", stockCode));
                if (stock == null) {
                    stock = new Stock();
                    String spell = GetPyByChinese.converterToFirstSpell(data.getString("f14"));
                    stock.setStockCode(data.getString("f12"));
                    stock.setStockName(data.getString("f14"));
                    stock.setStockType(key);
                    stock.setStockSpell(spell);
                    stock.setStockGid(key + data.getString("f12"));
                    stock.setIsLock(0);
                    stock.setIsShow(0);
                    stock.setAddTime(new Date());
                    stockMapper.insert(stock);
                    sb.append("新增股票：").append(stock.getStockName()).append(stock.getStockCode()).append("/n");
                }
            }
            log.info(key + "股新增股票：{}", sb.toString());
        }

    }
}